let db=require('../db/dbmanager');
const log4js        = require('../data/log');
const logger        = log4js.getLogger('db');

/**
 * 子通道数据库操作
 */
let Channel={
    updateOnline:function(parentId,deviceid,online){
        let p = new Promise(function(resolve,reject){
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            let newParam = {
                $deviceid:deviceid,
                $parentid:parentId,
            };
            db.sqliteDB.all(sql,newParam,function(err,rows){
                if(!err){
                    // 更新
                    let newsql;
                    if(rows && rows.length){
                        newsql = "UPDATE CHANNEL SET online=$online ";
                        if(online){
                            newParam.$last_heart=(new Date()).getTime();
                            newsql += ", last_heart=$last_heart "
                        }
                        newsql += " WHERE deviceid=$deviceid AND parentid=$parentid";
                    }else{
                        newParam.$last_heart=(new Date()).getTime();
                        newsql = "INSERT INTO CHANNEL(deviceid,parentid,online,last_heart) VALUES ($deviceid,$parentid,$online,$last_heart)";
                    }
                    db.sqliteDB.run(newsql,Object.assign(newParam,{
                        $online        : online
                    }));
                    resolve(rows)
                }else{
                    reject();
                }
            });
        });
        return p;
    },
    // 更新截图
    updateSnap:function(snap, parentid, deviceid){
        let p = new Promise(function(resolve,reject){
        // 是否有记录，不存在 的话新增
        const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
        let newParam = {
            $deviceid:deviceid,
            $parentid:parentid
        };
        db.sqliteDB.all(sql,newParam,function(err,rows){
            if(!err){
                // 更新
                let newsql;
                if(rows && rows.length){
                    newsql = "UPDATE CHANNEL SET snap=$snap " +
                        " WHERE deviceid=$deviceid AND parentid=$parentid";
                }
                db.sqliteDB.run(newsql,Object.assign(newParam,{
                    $snap       : snap
                }));
                resolve(rows)
            }else{
                reject();
            }
        });
        });
        return p;
    },
    /**
     * 协议变更
     * @param {*} channelInfo 
     */
    updateProtocol: function(channelInfo){

    },
    // 更新设备信息，如果记录不存在就自动新增
    updateDeviceInfo: function(channelInfo){
        let p = new Promise(function(resolve,reject){
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            let newParam = {
                $deviceid:channelInfo.DeviceID.toString(),
                $parentid:channelInfo.ParentID.toString()
            };
            db.sqliteDB.all(sql,newParam,function(err,rows){
                if(!err){
                    // 更新
                    let newsql;
                    if(rows && rows.length){
                        newsql = "UPDATE CHANNEL SET online=1, " +
                            "name=$name," +
                            "manufacture=$manufacture," +
                            "model=$model," +
                            "owner=$owner," +
                            "civilcode=$civilcode," +
                            "address=$address," +
                            "registerway=$registerway," +
                            "secrecy=$secrecy," +
                            "last_heart=$last_heart," +
                            "rtsp_url=$rtsp_url" +
                            " WHERE deviceid=$deviceid AND parentid=$parentid";
                    }else{
                        newsql = "INSERT INTO CHANNEL(deviceid,parentid,online,name,manufacture,model,owner,civilcode,address,registerway,secrecy,last_heart,rtsp_url) " +
                        " VALUES " + 
                        "($deviceid,$parentid,1,$name,$manufacture,$model,$owner,$civilcode,$address,$registerway,$secrecy,$last_heart,$rtsp_url)";
                    }
                    if(!channelInfo.Address){
                        channelInfo.Address='';
                    }
                    db.sqliteDB.run(newsql,Object.assign(newParam,{
                        $name           : channelInfo.Name.toString(),
                        $manufacture    : channelInfo.Manufacturer.toString(),
                        $model          : channelInfo.Model.toString(),
                        $owner          : channelInfo.Owner.toString(),
                        $civilcode      : channelInfo.CivilCode.toString(),
                        $address        : channelInfo.Address.toString(),
                        $registerway    : channelInfo.RegisterWay.toString(),
                        $secrecy        : channelInfo.Secrecy.toString(),
                        $last_heart     : (new Date()).getTime(),
                        $rtsp_url       : channelInfo.rtsp_url
                    }));
                    resolve(rows)
                }else{
                    reject();
                }
            });
        });
        return p;
    },
    /**
     * 查询列表
     * @param {*} callback 
     */
    list: function(account){
        let p = new Promise(function(resolve, reject){
            const sql="SELECT * FROM CHANNEL WHERE parentid='" + account + "'";
            db.sqliteDB.queryData(sql,function(rows){
                resolve(rows);
            });
        });
        return p;
    },
    // TODO: 重置状态，camera的可能要修改
    reset:function(){
        let minTime = (new Date()).getTime()-60*10*1000;
        const sql = "UPDATE CHANNEL SET online=0 WHERE last_heart<" + minTime;
        logger.log(sql);
        db.sqliteDB.run(sql);
    },
    /**
     * 根据父通道删除所有子通道信息
     * @param {*} deviceid 
     */
    deleteByDeviceId: function(deviceid){
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentid";
        let paramChannel = {$parentid: deviceid};
        console.log(sqlChannel, paramChannel);
        db.sqliteDB.run(sqlChannel, paramChannel);
    }
};
module.exports=Channel;
